package modules::cuffdiff;

sub new {
  my ($class,$config,$tophat_dir)    = @_;

  my $self = {
               _path         => $config->{'PATH'      },
               _job_name     => $config->{'JOB_NAME'  },
               _genome       => $config->{'GENOME'    },
               _no_samples   => $config->{'NO_SAMPLES'},     
               _tophat_dir   => $tophat_dir,
               _samples      => $config->{'SAMPLES'    },
             };
  bless $self,$class;
  return $self;
}

sub prepare {
  my ($self,$cuffmerge_dir) = @_;
  my $job_name              = $self->{'_job_name'};
  my $path                  = $self->{'_path'};
 
  $self->{'_cuffmerge_out'} = $cuffmerge_dir . '/merged.gtf';

  my $cuffdiff_out         = $path .'/results/'. $job_name . '/Cuffdiff';
  print "Creating '$cuffdiff_out'...\n";
  
  $self->{'_cuffdiff_out'} = $cuffdiff_out;
  mkdir  $cuffdiff_out, 777; chmod(0777, $cuffdiff_out);
  
  return;
}

sub run {
  my ($self,$bam_dirs)      = @_;
  my $cuffdiff_out          = $self->{'_cuffdiff_out' };
  my $genome                = $self->{'_genome'       };
  my $tophat_dir            = $self->{'_tophat_dir'   };
  my $samples               = $self->{'_samples'      };
  my $cuffmerge_out         = $self->{'_cuffmerge_out'};
  my $no_samples            = scalar @$samples;

  my ($cmd,@bam_files,@labels); 
  map { 
        push @bam_files, "$tophat_dir/$_->[0]/accepted_hits.bam " 
      } @$samples;
  map { 
        push @labels,    "sample".$_    
      } 1..$no_samples; 
  my $bam_files = join( '', @bam_files );
  my $labels    = join( ',', @labels    );

  
  $cmd = qq(bsub -Is -n 4 -R "span[ptile=4] rusage[mem=5000]" )
       . qq(" cufflinks-1.3.0 cuffdiff -o $cuffdiff_out )
       . qq( -b $genome.fa -p 8 )
       . qq( -L $labels -u $cuffmerge_out )
       . qq( $bam_files");
   
  print "\n\nRUNNING COMMAND:\n$cmd\n\n";
  system($cmd);
  return;

}
1; 


